﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YXChatApiService.Application.AccountServices;
using YXChatApiService.Application.ChatRecordService;
using YXChatApiService.Application.ChatRecordService.Dtos;
using YXChatApiService.Filters;
using YXChatApiService.HubCommon;

namespace YXChatApiService.Controllers
{
    public class ChatRecordController:ApiControllerBase
    {
        private readonly IChatRecordAppService _chatRecordAppService;
        private readonly IAccountAppService _accountAppService;
        private readonly IHubContext<ChatHub, IChatService> _chatHub;

        public ChatRecordController(IChatRecordAppService chatRecordAppService, 
            IHubContext<ChatHub, IChatService> chatHub, 
            IAccountAppService accountAppService)
        {
            _chatRecordAppService = chatRecordAppService;
            _chatHub = chatHub;
            _accountAppService = accountAppService;
        }
        [HttpPost]
        [ResultDataFilter]
        public async Task CreateChatRecord(CreateChatRecordInput input)
        {
            await _chatRecordAppService.CreateChatRecord(input);
            // 通知对方
            var buddyClient= HubClients.AccountClients.FirstOrDefault(x => x.AccountNumber == input.RNumber);
            if (buddyClient != null)
            {
                MessageNotifyDto messageNotify = new MessageNotifyDto
                {
                    Account = _accountAppService.GetAccount(input.SNumber),
                    ChatRecordDto = new ChatRecordDto()
                    {
                        Content = input.Content,
                        CreateTime = input.CreateTime,
                        RNumber = input.RNumber,
                        SNumber = input.SNumber
                    }
                };
                await _chatHub.Clients.Client(buddyClient.ConnectionId).SendMessage(messageNotify);
            }
        }
        [HttpGet("{selfNumber}/{buddyNumber}")]
        [ResultDataFilter]
        public ChatRecordAccountDto GetChatRecord(string selfNumber,string buddyNumber)
        {
            return _chatRecordAppService.GetChatRecord(selfNumber,buddyNumber);
        }
        [HttpGet("{selfNumber}")]
        [ResultDataFilter]
        public List<ChatRecordAccountDto> GetChatRecordAll(string selfNumber)
        {
            return _chatRecordAppService.GetChatRecordAll(selfNumber);
        }
    }
}
